<?php

namespace Addons\ThinkSDK;
use Common\Controller\Addon;

/**
 * SNS通用开发者插件插件
 * @author yangweijie
 */

    class ThinkSDKAddon extends Addon{

        public $info = array(
            'name'=>'ThinkSDK',
            'title'=>'SNS通用开发者插件',
            'description'=>'集成ThinkSDK,并提供可以调用的接口',
            'status'=>1,
            'author'=>'yangweijie',
            'version'=>'0.1'
        );

        public $admin_list = array(
            'model'=>'Oauth',		//要查的表
			'fields'=>'*',			//要查的字段
			'map'=>'',				//查询条件, 如果需要可以再插件类的构造方法里动态重置这个属性
			'order'=>'id desc',		//排序,
			'list_grid'=>array(//这里定义的是除了id序号外的表格里字段显示的表头名，规则和模型里的规则一样
				'uid:用户id',
				'type:平台',
				'description:描述',
				'access_token:access_token',
				'expires_in:过期时间',
                'openid:openid',
                'status:状态',
				'id:操作:[DELETE]|删除'
			)
        );

        public function install(){
            if(!extension_loaded('curl')){
                session('addons_install_error', 'PHP的CURL扩展未开启');
                return false;
            }

            $hookModel = M('Hooks');
            if (!$hookModel->where('name = "thinksdk"')->find()) {
                $hookModel->add(array(
                        'name' => 'thinksdk',
                        'description' => 'thinksdk专门用的钩子',
                        'type' => 1,
                        'update_time' => time()
                    )
                );
                S('hooks', null);
                if (!$hookModel->where('name = "thinksdk"')->find())
                    session('addons_install_error', 'thinksdk钩子创建失败');
            }
            $sql = file_get_contents($this->addon_path . 'install.sql');
            $db_prefix = C('DB_PREFIX');
            $sql = str_replace('onethink_', $db_prefix, $sql);
            D()->execute($sql);
            $table_name = $db_prefix.'oauth';
            if(count(M()->query("SHOW TABLES LIKE '{$table_name}'")) != 1){
                session('addons_install_error', ',oauth表未创建成功，请手动检查插件中的sql，修复后重新安装');
                return false;
            }
            return true;
        }

        public function uninstall(){
            return true;
        }

        //实现的pageHeader钩子方法
        public function pageHeader($param){
            $config = $this->getConfig();
            echo $config['platformMeta'];
        }

        //实现的thinksdk钩子方法
        public function thinksdk(&$param){
            $config = $this->getConfig();
            switch ($param['action']) {
                case 'login':
                    $this->assign('third_login',$config['login_plugin']);
                    $this->display('login');
                    break;

                case 'call':
                    require_once $this->addon_path.'/lib/ThinkOauth.class.php';
                    $type = $param['type'];
                    $token = $param['token'];
                    $api = $param['api'];
                    if(!isset($token) || empty($token))
                        return array('status'=>0, 'info'=>'token不存在');
                    C("THINK_SDK_QQ", array(
                        'APP_KEY'=>$config['qq_ak'],
                        'APP_SECRET'=>$config['qq_sk'],
                        'CALLBACK'=>$config['url_callback'].'qq',
                    ));
                    C("THINK_SDK_SINA", array(
                        'APP_KEY'=>$config['sina_ak'],
                        'APP_SECRET'=>$config['sina_sk'],
                        'CALLBACK'=>$config['url_callback'].'sina',
                    ));

                    $sns = \ThinkOauth::getInstance($type, $token);
                    $data = $sns->call($api, $param['param']);
                    switch ($type) {
                        case 'qq':
                        case 'tencent':
                            if($data['ret'] == 0){
                                $param = array('status'=>1, 'data'=>$data);
                            }else{
                                $param = array('status'=>0, 'info'=>$data['msg']);
                            }
                            break;
                        case 'sina':
                        case 't163':
                        case 'x360':
                            if($data['error_code'] == 0){
                                $param = array('status'=>1, 'data'=>$data);
                            }else{
                                $param = array('status'=>0, 'info'=>$data['error']);
                            }
                            break;
                        case 'renren':
                            $param = array('status'=>0, 'info'=>$data['准备升级至v2接口']);
                            break;
                        case 'douban':
                            if(empty($data['code'])){
                                $param = array('status'=>1, 'data'=>$data);
                            }else{
                                $param = array('status'=>0, 'info'=>$data['msg']);
                            }
                            break;
                        case 'github':
                            if(empty($data['code'])){
                                $param = array('status'=>1, 'data'=>$data);
                            }else{
                                $param = array('status'=>0, 'info'=>$data);
                            }
                            break;
                        case 'google':
                        case 'msn':
                        case 'souhu':
                            $param = array('status'=>0, 'info'=>$data['请自行查找出'.$type.' api报错的通用条件']);
                            break;
                        case 'diandian':
                            if(!empty($data['meta']['status']) && $data['meta']['status'] == 200){
                                $param = array('status'=>1, 'data'=>$data);
                            }else{
                                $param = array('status'=>0, 'info'=>$data);
                            }
                            break;
                        case 'taobao':
                            if(empty($data['error'])){
                                $param = array('status'=>1, 'data'=>$data);
                            }else{
                                $param = array('status'=>0, 'info'=>$data['error_description']);
                            }
                            break;
                        case 'baidu':
                            if(empty($data['error_code'])){
                                $param = array('status'=>1, 'data'=>$data);
                            }else{
                                $param = array('status'=>0, 'info'=>$data['error_msg']);
                            }
                            break;
                        case 'kaixin':
                            if(empty($data['error_code'])){
                                $param = array('status'=>1, 'data'=>$data);
                            }else{
                                $param = array('status'=>0, 'info'=>$data['error']);
                            }
                            break;
                    }
                    break;
                # 获取token
                case 'check':
                    //TODO 改为自己的获取用户id方式
                    if(!$id = is_login())
                        $param = false;
                    $res = D('Addons://ThinkSDK/Oauth')->where("`uid` = {$id} AND `type` = '{$param['type']}'")->find();
                    if(!$res['status'] || strtotime($res['expires_in']) > time()){
                        $param = $res;
                    }else{
                        D('Addons://ThinkSDK/Oauth')->where("`uid` = {$id} AND `type` = '{$param['type']}'")->save(array('status'=>0));
                        $param = false;
                        //TODO跳转自己的登录页
                    }
                    break;
            }
        }
    }
